package com.xiaolanshu.controller;

import com.xiaolanshu.entity.Collection;
import com.xiaolanshu.interceptor.UserHolder;
import com.xiaolanshu.service.CollectionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/collection")
public class CollectionController {

    @Autowired
    private CollectionService collectionService;

    @PostMapping("/{noteId}")
    public ResponseEntity collection(@PathVariable Long noteId){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();

        //根据用户id和笔记id查找收藏信息
        Collection collection = collectionService.findCollection(userId,noteId);

        //如果表中不存在收藏信息则添加记录
        if(collection == null){
            Collection collectionNew = new Collection();
            collectionNew.setUserId(userId);
            collectionNew.setNoteId(noteId);
            collectionNew.setCollection(1);
            collectionService.saveCollection(collectionNew);
        }
        //收藏信息存在，1为收藏，0为取消收藏
        else {
            //收到请求时，如果collection为1，则修改表的数据为0
            if (collection.getCollection() == 1){
                collection.setCollection(0);
                collectionService.updateById(collection);
                return ResponseEntity.status(200).body("取消收藏");
            }
            //收到请求时，如果collection为0，则修改表的数据为1
            else{
                collection.setCollection(1);
                collectionService.updateById(collection);
            }
        }
        return ResponseEntity.status(200).body("收藏成功");
    }

}
